<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Cate extends Controller_Base{

    public function action_index()
    {

        $u=$this->request->param('id');

        if(empty($u)){

            if($this->request-> is_ajax()){

                $result=array();

                $result['code']='0x0000x';

                exit(json_encode($result));

            }

            $this->redirect("/");

        }

        $cate_model=new Model_Cate();

        $cate=$cate_model->getInfoByUrl($u);

        if(empty($cate)){

            if($this->request-> is_ajax()){

                $result=array();

                $result['code']='0x0000x';

                exit(json_encode($result));

            }

            $this->redirect("/");

        }

        $pageSize=Kohana::$config->load('item.cate')?Kohana::$config->load('item.cate'):50;

        if($this->request-> is_ajax()){

            $page=intval($this->request->post("page"))?intval($this->request->post("page")):1;

        }
        else{

            $page=intval($this->request->query("page"))?intval($this->request->query("page")):1;

        }

        $page=$page>1?$page:1;

        $offset=$pageSize*($page-1);

        $posts = Cache::instance()->get('cate_list'.$cate['id']."-".$offset, null);

        if(empty($posts)){

            $posts=$cate_model->getPostInfo($cate['id'],$offset,$pageSize);

            Cache::instance()->set('cate_list'.$cate['id']."-".$offset, $posts, 100);

        }
        
        if($this->request-> is_ajax()){

            foreach ($posts as $key => $value) {

                $posts[$key]['image']=Lib_Image::getPostImage($value['id'],$value['images'],260);
                
            }

            $result=array();

            $result['list']=$posts;

            exit(json_encode($result));

        }

        $total = Cache::instance()->get('cate_items'.$cate['id'], null);

        if(empty($total)){

            $total=$cate_model->getItems($cate['id']);

            Cache::instance()->set('cate_items'.$cate['id'], $total, 100);

        }

        $url="/cate/".$u;

        $view=View::factory('cate/index');

        $view->page=$page;

        $view->url=$url;

        $view->pages=ceil($total/$pageSize);

        $view->u=$u;

        $view->posts=$posts;

        $view->total=$total;

        $this->template->title ="'Cate'-".$u;

        $this->template->content =$view;

     }
    
}
?>